import sys
from subprocess import Popen, PIPE
from csv import reader
from pdb import set_trace

class GrabMusic(object):
    """
    Given a URL with video / audio content, will download
    the video using youtube-dl and then extact and encode
    the audio using avconv.
    """
    def __init__(self):
        pass

    def get_urls(self,filename):
        """
        Get urls from a file containing urls.
        """
        urls = []
        with open(filename,mode='ro') as f:
            csv_reader = reader(f)
            for r in csv_reader:
                if r[0][0] == "#":
                    pass
                else:
                    urls.append(r[0])
        return urls

    def get_music(self,url):
        """
        Download the youtube video and encode audio.
        """
        proc = Popen(['youtube-dl','--get-title',url],stdout=PIPE)
        title = "%s.mp3"%(proc.stdout.read()[:-1])
        download = Popen(['youtube-dl',url,'-o','-'],stdout=PIPE)
        conv = Popen(['avconv','-i','-','-ar','44100','-ac','2','-acodec','libmp3lame','-aq','3',title],stdin=download.stdout)
        conv.wait()
        download.close()
        out, err = conv.communicate()
        return out, err

if __name__=='__main__':
    filename = sys.argv[1]
    yd = GrabMusic()
    urls = yd.get_urls(filename)
    failed = []
    for url in urls:
        try:
            out, err = yd.get_music(url)
        except:
            failed.append(url)
    print "The following urls failed:", failed
